const libUI = {}

// 获取本地配置 - get缓存
libUI.getLocalCache = () => {
  // 默认返回
  return new Promise((resolve, _) => {  resolve(false) })
}

// 保存本地配置 - save缓存
libUI.saveLocalCache = (data = {}) => {
  return new Promise((resolve, _) => {  resolve(false) })
}

libUI.cancel = () => {
  return new Promise((_, reject) => reject(false))
}

libUI.confirm = (data = {}) => {
  // 没有返回值
  return new Promise((_, reject) => reject(false))
}

export default libUI;


libUI.requestBase = (url, options = {}) => {
  const defaultOption = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    }
  }

  const data = options.body
  let method = options.method || ''
  method = method.toUpperCase()
  if (method) {
    options.method = method
  }
  if (data && method == 'POST') {
    if (typeof data != 'string') {
      // 这个是 fetch 的 body
      const dataString = JSON.stringify(data) || ''
      options.body = dataString
      defaultOption.headers['Content-Length'] = dataString.length
    } else {
      defaultOption.headers['Content-Length'] = data.length
    }
  }

  const fetchOptions = Object.assign({}, defaultOption, options)

  return fetch(url, fetchOptions).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  }).catch(error => {
    console.error('Fetch error:', error);
    throw error;
  });
}

libUI.requestGet = (ApiUrl, data = {}) => {
  let url = ApiUrl
  if (data) {
    url += '?'
    let i = 0
    for (const key of Object.keys(data)) {
      if (i > 0) {
        url += '&'
      }
      url += '' + key + '=' + data[key]
    }
  }
  return libUI.requestBase(url)
}

libUI.requestPost = (ApiUrl, data) => {
  const options = {
    method: 'POST',
    body: data
  }
  return libUI.requestBase(ApiUrl, options)
}